package com.zzw.controller;

import com.zzw.entity.Result;
import com.zzw.message.MessageConstant;
import com.zzw.pojo.User;
import com.zzw.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @PostMapping("/login")
    public Result findAll(@RequestBody User user, HttpSession session) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        User u = userService.findUser(user);
        if (u!=null){
            session.setAttribute("username",u.getUsername());
            return new Result(true, MessageConstant.LOGIN_SUCCESS,u);
        }
        return new Result(false,MessageConstant.LOGIN_FAIL,null);
    }
    @PostMapping("/add")
    public Result addUser(@RequestBody User user){
        try {
            userService.addUser(user);
            Result result = new Result(true, MessageConstant.ADD_USER_SUCCESS);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        Result result = new Result(false, MessageConstant.ADD_USER_FAIL);
        return result;
    }
    @PostMapping("/updatePsw")
    public Result updatePassword(@RequestBody User user,@RequestParam String newPassword1,@RequestParam String newPassword2) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        User oldUser = userService.findUser(user);
        if (!newPassword1.equals(newPassword2)){
            return new Result(false,MessageConstant.UPDATE_PASSWORD_FAIL3);
        }
        if (oldUser != null){
            user.setPassword(newPassword1);
            try {
                userService.updateUser(user);
                return new Result(true,MessageConstant.UPDATE_PASSWORD_SUCCESS);
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(false,MessageConstant.UPDATE_PASSWORD_FAIL);
            }
        }
        return new Result(false,MessageConstant.UPDATE_PASSWORD_FAIL2);
    }

    /*此方法为测试使用*/
    @GetMapping("/findAll")
    public Result findAll(){
        try {
            List<User> list = userService.findAll2();
            return new Result(true,"查询用户成功",list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"查询用户失败");
        }
    }
}
